import { getGroupTree, createGroup, getDetail } from '@/services/group';

function formatTree(list) {
    if (!list || list.length === 0) {
        return []
    }
    list = list.map((value) => {
        let title = value.title
        if (value.type === 'device' && !value.title) {
            title = '未分配人员';
        }
        let node = {
            title: title,
            key: value.id,
            value: value.id,
            type: value.type,
            isTmp: value.isTmp,
            groupId: value.groupId || '',
            sn: value.deviceSn || '',
            children: formatTree(value.children),
        }
        if (value.type === 'device') {
            node.isOnline = value.isOnline ? value.isOnline : 0;
            node.isDisabled = value.isDisabled ? value.isDisabled : 0;
        }
        return node;
    });
    return list;
}

export default {
    namespace: 'group',

    state: {
        groupTree: [],
        detail: {},
    },

    effects: {
        *fetchGroupTree({ payload, callback }, { call, put }) {
            const response = yield call(getGroupTree, payload);

            yield put({
                type: 'groupTree',
                payload: response,
            });
            if (response && callback) {
                callback(response);
            }
        },
        *create({ payload, callback }, { call, put }) {
            const response = yield call(createGroup, payload);
            if (response && callback) {
                callback(response);
            }
        },

        *fetchDetail({ payload, callback }, { call, put }) {
            const response = yield call(getDetail, payload);
            yield put({
                type: 'detail',
                payload: response,
            });
            if (response && callback) {
                callback(response);
            }
        },
    },

    reducers: {
        groupTree(state, action) {
            return {
                ...state,
                groupTree: formatTree(action.payload.data)
            }
        },
        detail(state, action) {
            return {
                ...state,
                detail: action.payload.data
            }
        },
    },
};
